<template>
  <div class="detail-page">
    <template v-if="currentClass?.class_name">
      <div class="top">
        <span class="name"
          >{{ currentClass?.grade_name
          }}{{ currentClass?.class_name || '-' }}</span
        >
        <div class="search">
          <el-input
            class="input"
            placeholder="输入姓名/学号搜索学生"
            :prefix-icon="Search"
            v-model="searchContent"
          ></el-input>
          <p v-if="!isTarget" class="class" @click="selectClassVisible = true">
            {{ currentClass?.grade_name }}{{ currentClass?.class_name || '-' }}
            <el-icon>
              <ArrowRight />
            </el-icon>
          </p>
          <button v-if="isTarget" @click="deleteClass" class="disband">
            <img
              src="@/assets/images/class-manage/disband-light-icon.svg?url"
            />
            解散
          </button>
        </div>
      </div>
      <teaching-teacher
        :teachingTeacher="teachingTeacher"
        :targetInfo="targetInfo"
        @update-target-visible="getTargetMsg"
      ></teaching-teacher>
      <student-manage
        :currentClass="currentClass"
        :studentList="studentList"
        :total="total"
      ></student-manage>
      <disband-class
        :id="currentClassId"
        v-model="disbandVisible"
        @confirm-disband="handleDisband"
      ></disband-class>
      <class-select
        :currentClass="currentClass"
        :classList="classList"
        v-model="selectClassVisible"
        @select-class="changeClass"
      ></class-select>
    </template>
    <div v-else class="empty">
      <img src="@/assets/images/assignment/wrong-question-tip.png" />
      <p class="tip">
        {{
          authStore.nowIsSmartRoomCode
            ? '暂无爱学班班级数据，请联系管理员创建'
            : isTarget
              ? '暂无靶向班班级数据，请在任意选择学生处创建'
              : `暂无${isTeaching ? '教学班' : '行政班'}班级数据，请联系管理员创建`
        }}
      </p>
    </div>
  </div>
</template>
<script setup>
import TargetClass from './TargetClass.vue'
import ClassSelect from './ClassSelect.vue'
import DisbandClass from './DisbandClass.vue'
import TeachingTeacher from './TeachingTeacher.vue'
import StudentManage from './StudentManage.vue'
import { Search, ArrowRight } from '@element-plus/icons-vue'
import { ref, reactive, watch, computed } from 'vue'
import {
  getClassList,
  getTargetInfo,
  getClassTeacher,
  getTargetStudents,
  getAdministrationStudents
} from '@/apis/class-manage/index'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores'
import { debounce } from '@/utils/debounce.js'

const authStore = useAuthStore()
const route = useRoute()
const router = useRouter()
const searchContent = ref('')
const selectClassVisible = ref(false)

const isTarget = computed(() => {
  return route.path.indexOf('target') > -1
})

const isTeaching = computed(() => {
  return route.name.indexOf('teaching') > -1
})

// 解散靶向班
const disbandVisible = ref(false)
const currentClassId = ref(0)
const deleteClass = () => {
  currentClassId.value = Number(route.query.classId)
  disbandVisible.value = true
}

const handleDisband = () => {
  router.replace('/classManage/target')
}

// 班级选择
const currentClass = ref()
const classList = ref([])
const getClass = async () => {
  classList.value = []
  const params = {
    teacher_id: authStore.userInfo.userId,
    role_code: authStore.nowGlobalRole.role_code
  }
  // if (authStore.nowIsSmartRoomCode) {
  //   params.role_code = authStore.nowGlobalRole.role_code
  // }
  const { data } = await getClassList(params)
  if (authStore.nowIsSmartRoomCode) {
    classList.value = data?.zhixi_class || []
  } else {
    const list = data?.admini_and_teaching_class || []
    classList.value = list.filter(item =>
      isTeaching.value
        ? item.class_type_name === '教学班'
        : item.class_type_name === '行政班'
    )
  }
  // 默认从缓存中获取上次选中的班级
  const cachedClassId = sessionStorage.getItem('ai-learn-class-manage-classId')
  if (cachedClassId) {
    currentClass.value = classList.value.find(item => item.id === cachedClassId)
  } else {
    currentClass.value = classList.value[0]
  }
}

const changeClass = val => {
  sessionStorage.setItem('ai-learn-class-manage-classId', val.id)
  currentClass.value = val
}

// 教师列表
const teachingTeacher = ref()
const getTeacher = async () => {
  const { data } = await getClassTeacher({
    school_id: authStore.userInfo.school_id,
    class_id: currentClass.value.id
  })
  teachingTeacher.value = data || []
}

const targetInfo = ref()
const getTargetMsg = async () => {
  const { data } = await getTargetInfo({ class_ids: currentClass.value.id })
  targetInfo.value = data?.[0] || {}
}

// 学生列表
const page = reactive({
  current: 1,
  size: 100
})
const total = ref(0)
const studentList = ref([])
const getStudents = async () => {
  const params = {
    page: page.current,
    page_size: page.size,
    school_id: authStore.userInfo.school_id,
    class_id: currentClass.value.id,
    keyword: searchContent.value
  }
  const { data } = await getAdministrationStudents(params)
  total.value = data.total || 0
  studentList.value = data.list || []
}

// 获取靶向班学生列表
const getTargetList = async () => {
  const params = {
    page: page.current,
    page_size: page.size,
    targeted_class_id: currentClass.value.id,
    keyword: searchContent.value
  }
  const { data } = await getTargetStudents(params)
  studentList.value = data.list || []
  total.value = data.total || 0
}

watch(
  () => route.name,
  async () => {
    if (!isTarget.value) {
      await getClass()
    } else {
      currentClass.value = {
        class_name: route.query.className,
        id: route.query.classId,
        grade_id: route.query.gradeId
      }
    }
  },
  {
    immediate: true
  }
)

watch(
  () => currentClass.value,
  val => {
    if (val) {
      if (isTarget.value) {
        getTargetMsg()
        getTargetList()
      } else {
        getTeacher()
        getStudents()
      }
    } else {
      teachingTeacher.value = {}
    }
  },
  {
    immediate: true
  }
)

watch(
  () => searchContent.value,
  () => {
    debounce(() => {
      if (isTarget.value) {
        getTargetList()
      } else {
        getStudents()
      }
    }, 500)
  }
)

watch(
  () => authStore.nowGlobalRole.role_code,
  () => {
    getClass()
  }
)
</script>
<style lang="less" scoped>
.detail-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;

  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1.5px solid #e6e7e8;
    padding-bottom: 18px;

    .name {
      color: #040b1ad9;
      font-size: 22px;
      font-weight: 700;
    }

    .search {
      display: flex;
      align-items: center;
      gap: 20px;

      .class {
        display: flex;
        align-items: center;
        justify-content: space-between;
        cursor: pointer;
        width: 198px;
        height: 36px;
        border: 1px solid #b2cdff;
        border-radius: 5px;
        padding: 0 17px;
        font-size: 14px;
        color: #b2cdff;
      }

      .input {
        width: 294px;
        border-color: #b2cdff;

        :deep(.el-input__wrapper) {
          height: 36px;
          box-shadow: unset;
          border: 1px solid #b2cdff;
          border-radius: 5px;
          font-size: 16px;

          * {
            color: #b2cdff;
          }

          .el-input__inner::placeholder {
            color: #b2cdff;
            font-size: 14px;
          }
        }
      }

      .disband {
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 12px;
        width: 102px;
        height: 36px;
        border-radius: 5px;
        border: 1px solid @color-function-danger-dark;
        background-color: @color-function-danger-dark;
        color: #fff;
        font-size: 18px;
        font-weight: 700;

        img {
          width: 15px;
        }
      }
    }
  }

  .empty {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 600px;

    img {
      width: 300px;
    }

    .tip {
      color: #333;
      font-size: 14px;
      margin-top: 20px;
    }
  }
}
</style>
